package cn.hxt.user.controller;


import cn.hxt.basic.util.AjaxResult;
import cn.hxt.basic.util.PageList;
import cn.hxt.user.domain.User;
import cn.hxt.user.dto.UserDto;
import cn.hxt.user.query.UserQuery;
import cn.hxt.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {

   /* @GetMapping("/{id}")
    public User getById(@PathVariable("id") Long id){
        return null;
    }*/

   @Autowired
   private IUserService userService;

    /**
     * 写接口三要数：
     * 1请求地址是什么
     *
     * @return
     */


    //新增and修改
    @PostMapping("/addOnUpdate")
    @ApiOperation(value = "用户修改及新增",notes = "如果有id就是修改，没有就是新增")
    public AjaxResult addOnUpdate(@RequestBody User user){
        try {
            //判断是否携带id
            if(user.getId() ==null){
                //没id就新增
                userService.add(user);
            }else{
                //有就是修改
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //打印提示
            return AjaxResult.me().setSuccess(false).setMessage("业务繁忙，请稍后！！！");
        }

    }



    //删除一条数据
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            //成功
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //使用链式
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }


    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            userService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    //分页
    @PostMapping("/page")
    public PageList<User> query(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }


    //获取全部数据
    @GetMapping("/list")
    public List<User> findAll(){
        return userService.queryAll();
    }


   //获取一条数据    GET
    @GetMapping("/{id}")
    public User findById(@PathVariable("id") Long id){
        return  userService.queryById(id);
    }


    /**
     * 手机注册
     * @param userDto
     * @return
     */
    @PostMapping("/phone/register")
    private AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

}
